package com.tingyu.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //定义切面和拦截范围
    @Pointcut("execution(* com.tingyu.blog.web.*.*(..))")
    public void log(){}

    //切面前
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();    //获取url
        String ip = request.getRemoteAddr();    //获取IP地址
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();     //获取类方法名
        Object[] args = joinPoint.getArgs();    //获取请求参数
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);    //构造requestLog对象

        logger.info("Request : {}",requestLog);
    }

    //切面后
    @After("log()")
    public void doAfter(){
//        logger.info("--------doAfter---------");
    }

    //切面后返回
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }



    //内部类
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = this.url;
            this.ip = this.ip;
            this.classMethod = this.classMethod;
            this.args = this.args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
